<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class UpdateCartItemRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     */
    public function authorize(): bool
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array<string, \Illuminate\Contracts\Validation\ValidationRule|array<mixed>|string>
     */
    public function rules(): array
    {
        return [
            'item_id' => 'required|exists:cart_items,id',
            'quantity' => 'required|integer|min:1|max:99',
        ];
    }

    /**
     * Get custom messages for validator errors.
     */
    public function messages(): array
    {
        return [
            'item_id.required' => '请选择要更新的商品',
            'item_id.exists' => '购物车商品不存在',
            'quantity.required' => '请输入数量',
            'quantity.integer' => '数量必须是整数',
            'quantity.min' => '数量不能少于1',
            'quantity.max' => '数量不能超过99',
        ];
    }

    /**
     * Configure the validator instance.
     */
    public function withValidator($validator): void
    {
        $validator->after(function ($validator) {
            // 验证购物车项是否属于当前用户
            if ($this->item_id) {
                $cartItem = \App\Models\CartItem::with('cart')->find($this->item_id);
                if ($cartItem && $cartItem->cart->user_id !== auth()->id()) {
                    $validator->errors()->add('item_id', '无权操作此商品');
                }
            }
        });
    }
}